<?php
namespace app\index\controller;
use think\Session;
use app\index\model\User as Users;
use app\index\model\News;
use app\index\validate\UserVerify;
use app\index\validate\AddVerify;
use think\Loader;
use think\db;

class User extends ComContro{

	//用户登录方法 调用view显示登录页面
	public function login(){
		return view();
	}

	//登录时判断用户名和密码是否正确，和数据库中的值作比较
	public function userLogin(){
		$user = new Users;
		$name = input('post.username');
		$pwd  = input('post.password');
		// $res = $user->where([
		// 	'username' => $name,
		// 	'password' => $pwd
		// ])->find()->toArray();
		// print_r($res);
		// dump($res);
		
		if(!empty($name) && !empty($pwd)){
		   $sucMsg = "$name 登录成功！！";
		   $errMsg = "用户名或密码错误，请重新输入！！";
		
			$res = $user->where([
				'username' => $name,
				'password' => $pwd
			])->find();

			if(empty($res)){
				echo "<script type='text/javascript'>alert('$errMsg');location.href='/index/user/login';</script>"; 
				// header('Location:/index/user/login');	
			}else{

				// echo "<script type='text/javascript'>alert('$sucMsg');location.href='/index/user/admin';</script>"; 
				 // php的header函数实现页面跳转
				 header('Location:/index/admin/admin');

				Session::set('user',[
					'id' => $res->id,
					'username' =>$res->username
				]);		
			}
		}else{
		echo "<script type='text/javascript'>alert('$errMsg');location.href='/index/user/login';</script>"; 
		}
	}
	//用户注册页面
	public function regist(){
		$error="";
		if(Session::has('error')){
			$error = Session::get('error');
			Session::delete('error');
		}
			return view('',['msg'=>$error]);
	}
	//用户注册的数据处理
	public function regSave(){
		$user = new Users;
		$usenameReg = input('post.username');
		$pwdReg		= input('post.password');

		//如果输入的用户名和密码不为空，就判断值是否合法 调用验证类
		//验证失败输出错误提示 验证合法值 执行下一步添加数据
		if(!empty($usenameReg) && !empty($pwdReg)){
			//验证值
			$data = [
				'username' => $usenameReg ,
				'password' => $pwdReg
			];
			$validate = Loader::validate('UserVerify');
			if(!$validate->check($data)){
				$error = $validate->getError();
				session::set('error',$error);
				header('Location:/index/user/regist');
			}else{
				$user->username = $usenameReg;
				$user->password = $pwdReg;

				$r = $user->save();
				if($r){
					$this->success("恭喜您，注册成功！！");
				}else{
					$this->error("很遗憾，注册失败。。。");
				}
				echo "注册成功！";
			}
		}
	}
	//用户注销
	public function logout(){
		Session::delete('user',null);
		return header('Location:/index/user/login');
	}
}

